package com.geostar.constructionland.attachment.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.Map;

public class JacksonUtil {

  public static ObjectMapper objectMapper = new ObjectMapper();

  /**
   * 使用泛型方法，把json字符串转换为相应的JavaBean对象。
   * (1)转换为普通JavaBean：readValue(json,Student.class)
   * (2)转换为List,如List<Student>,将第二个参数传递为Student
   * [].class.然后使用Arrays.asList();方法把得到的数组转换为特定类型的List
   */
  public static <T> T readValue(String jsonStr, Class<T> valueType) {
    try {
      return objectMapper.readValue(jsonStr, valueType);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }

  /**
   * json数组转List
   */
  public static <T> T readValue(String jsonStr, TypeReference<T> valueTypeRef) {
    try {
      return objectMapper.readValue(jsonStr, valueTypeRef);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }

  /**
   * 把JavaBean转换为json字符串
   */
  public static String toJson(Object object) {
    try {
      return objectMapper.writeValueAsString(object);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return null;
  }

  public static Map<String, Object> toMap(Object object) {
    return objectMapper.convertValue(object, Map.class);
  }

  public static <T> T fromMap(Map<String, Object> map, Class<T> valueType) {
    return objectMapper.convertValue(map, valueType);
  }
}
